<?php

namespace App\Http\Middleware;

use App\Models\AdminUsersModel;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserInfoMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws Exception
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $loginCheck = Auth::guard()->check();
        if($loginCheck)
        {
            $model = AdminUsersModel::query()
                ->leftJoin('admin_users_related', 'admin_users_related.user_id', '=', 'admin_users.id')
                ->where('admin_users.id', auth()->user()->id)
                ->select('user_id', 'main_id')->first();

            define('USERID', $model->user_id);
            define('MAINID', $model->main_id === 0 ? $model->user_id : $model->main_id);
            define('ISMAIN', $model->main_id === 0 ?? false);
            define('ISADMIN', auth()->user()->id === 1 ?? false);
        }
        return $next($request);
    }
}
